【问题标题】:Intermittent memory corruption errors in JNA callsJNA 调用中的间歇性内存损坏错误
【发布时间】:2018-11-29 07:32:26
【问题描述】:

我们有一个非常简单的要求,即从 Java 调用几个本机函数。我们正在使用 JNA 进行这些本地调用。

编辑:我们没有任何自定义本机代码。我们正在调用 Linux Kernel C 库函数。

我们遇到了非常奇怪的内存损坏错误,例如

  • `/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el7_5.x86_64/jre/bin/java' 中的错误:malloc():内存损坏:0x00007f9b7849fc40李>
  • `/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el7_5.x86_64/jre/bin/java' 中的错误:损坏的大小与 prev_size:0x00007f253c4470f0
  • SIGSEGV (0xb)

程序甚至有时会挂断。这些错误是间歇性的。

在 JNA 调用中使用结构的一些标准示例/文档会很有帮助。


这是我们的具有原生函数的库包装器:

https://github.com/tmtsoftware/csw/blob/master/csw-time-client/src/main/scala/csw/time/client/internal/TimeLibrary.java

这些是映射到 C 中结构的原生模型:

https://github.com/tmtsoftware/csw/tree/master/csw-time-client/src/main/scala/csw/time/client/internal/native_models

这就是我们访问库函数的方式:

val timeVal = new NTPTimeVal()
TimeLibrary.ntp_gettimex(timeVal)
println(timeVal.tai)

您可以参考 TimeServiceImpl.scala 以获得更清晰的信息。

https://github.com/tmtsoftware/csw/blob/master/csw-time-client/src/main/scala/csw/time/client/internal/TimeServiceImpl.scala

谁能告诉我们我们到底做错了什么?

【问题讨论】:

  • 本机代码中很可能出错。可以展示一下吗?
  • 我们正在进行 3 个本地调用,所有调用都内置在 Linux 内核 C 库代码中。我们还没有编写任何自定义 C 代码。

标签: java c memory-leaks native jna


【解决方案1】:

ntptimeval及相关结构中有一些保留字段:

struct ntptimeval
{
  struct timeval time;  /* current time (ro) */
  long int maxerror;    /* maximum error (us) (ro) */
  long int esterror;    /* estimated error (us) (ro) */
  long int tai;     /* TAI offset (ro) */

  long int __glibc_reserved1;
  long int __glibc_reserved2;
  long int __glibc_reserved3;
  long int __glibc_reserved4;
};

your code 中没有的:

public class NTPTimeVal extends Structure {
    public TimeVal time;        /* Current time */
    public Long maxerror;       /* Maximum error */
    public Long esterror;
    public int tai;
}

如果这些保留字段恰好在您的 glibc 版本中使用,则可以解释堆损坏。

我还会仔细检查您返回的数据。如果某些字段包含奇怪的值,则可能意味着字段大小/对齐问题,这也可能表明结构比它需要的短。

【讨论】:

  • 非常感谢您的回答。我们曾使用 Linux 手册页 (man7.org/linux/man-pages/man3/ntp_gettime.3.html) 在我们的 JNA 代码中编写结构字段,结果证明这是错误的根源。新结构似乎运行良好。再次感谢您:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 2011-07-14
  • 2010-09-06
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多