This is an automated email from the ASF dual-hosted git repository.

pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git


The following commit(s) were added to refs/heads/trunk by this push:
     new 9727f3eade replace casts long to int with Math.toIntExact (#1072)
9727f3eade is described below

commit 9727f3eade42fcaea981e98f5237a3d9b60ecb05
Author: PJ Fanning <[email protected]>
AuthorDate: Thu May 14 11:26:06 2026 +0100

    replace casts long to int with Math.toIntExact (#1072)
    
    * Replace unsafe (int) long casts with Math.toIntExact()
    
    Replace explicit (int) casts of long values with Math.toIntExact() to
    detect integer overflow at runtime rather than silently truncating.
    
    Changes cover:
    - hemf emf records: HemfComment, HemfFill, HemfPalette, HemfDraw, HemfFont
    - hpsf: Section, Array, Vector, Property, PropertySet, PropertySetFactory, 
VariantSupport
    - poifs/crypt: CryptoAPIDecryptor, ChunkedCipherOutputStream, XORDecryptor, 
XOREncryptor
    - poi-ooxml XSSF: XSSFConditionalFormattingRule, XSSFDxfStyleProvider, 
XSSFOptimiser,
      XSSFChildAnchor, XSSFFontFormatting, XSSFDataBarFormatting, XSSFColor, 
XSSFTableStyle,
      XSSFWorkbook, XSSFSimpleShape, XSSFName, ColumnHelper
    - poi-ooxml XSLF: XSLFSimpleShape, XSLFSheet, XSLFTabStop, XSLFDrawing
    - poi-ooxml XDDF: XDDFDataSourcesFactory
    - hwpf: PlfLfo, RecordUtil
    - util: IOUtils
    - poifs/nio: ByteArrayBackedDataSource
    
    Guarded casts (already behind Integer.MAX_VALUE checks) and casts of
    floating-point or char values are intentionally left unchanged.
    
    Co-authored-by: Copilot <[email protected]>
    
    Co-authored-by: pjfanning <[email protected]>
    
    * Fix test failures: revert (int) cast for EMF uint32 identifiers and 
palette/brush indices, fix PropertySetFactory for large sectionCount
    
    Agent-Logs-Url: 
https://github.com/pjfanning/poi/sessions/1fcc029e-f25e-4e46-be29-fc0831ec0ee1
    
    Co-authored-by: pjfanning <[email protected]>
    
    * Address review comments: use Math.toIntExact with try/catch in 
PropertySetFactory, keep (Long) cast in XSSFChildAnchor
    
    Agent-Logs-Url: 
https://github.com/pjfanning/poi/sessions/1fcc029e-f25e-4e46-be29-fc0831ec0ee1
    
    Co-authored-by: pjfanning <[email protected]>
    
    * exceptions
    
    * Update poi-integration-exceptions.csv
    
    * Update TestAllFiles.java
    
    ---------
    
    Co-authored-by: copilot-swe-agent[bot] 
<[email protected]>
    Co-authored-by: pjfanning <[email protected]>
---
 .../java/org/apache/poi/stress/TestAllFiles.java   |  3 ++
 .../org/apache/poi/xslf/usermodel/XSLFDrawing.java |  6 ++-
 .../apache/poi/xslf/usermodel/XSLFSimpleShape.java |  7 ++-
 .../org/apache/poi/xslf/usermodel/XSLFTabStop.java |  2 +-
 .../apache/poi/xssf/usermodel/XSSFChildAnchor.java |  8 +--
 .../org/apache/poi/xssf/usermodel/XSSFColor.java   |  2 +-
 .../usermodel/XSSFConditionalFormattingRule.java   |  4 +-
 .../poi/xssf/usermodel/XSSFDataBarFormatting.java  |  4 +-
 .../poi/xssf/usermodel/XSSFDxfStyleProvider.java   |  2 +-
 .../poi/xssf/usermodel/XSSFFontFormatting.java     |  2 +-
 .../org/apache/poi/xssf/usermodel/XSSFName.java    |  6 +--
 .../apache/poi/xssf/usermodel/XSSFOptimiser.java   |  2 +-
 .../apache/poi/xssf/usermodel/XSSFSimpleShape.java |  4 +-
 .../apache/poi/xssf/usermodel/XSSFTableStyle.java  |  4 +-
 .../apache/poi/xssf/usermodel/XSSFWorkbook.java    |  6 +--
 .../poi/xssf/usermodel/helpers/ColumnHelper.java   |  2 +-
 .../apache/poi/hemf/record/emf/HemfComment.java    | 23 +++++----
 .../org/apache/poi/hemf/record/emf/HemfDraw.java   | 14 +++---
 .../org/apache/poi/hemf/record/emf/HemfFill.java   | 58 +++++++++++-----------
 .../org/apache/poi/hemf/record/emf/HemfFont.java   |  2 +-
 .../apache/poi/hemf/record/emf/HemfPalette.java    | 23 +++++----
 .../java/org/apache/poi/hwpf/dev/RecordUtil.java   |  2 +-
 .../java/org/apache/poi/hwpf/model/PlfLfo.java     |  2 +-
 poi/src/main/java/org/apache/poi/hpsf/Array.java   |  4 +-
 .../main/java/org/apache/poi/hpsf/Property.java    |  2 +-
 .../main/java/org/apache/poi/hpsf/PropertySet.java | 10 ++--
 .../org/apache/poi/hpsf/PropertySetFactory.java    | 10 +++-
 poi/src/main/java/org/apache/poi/hpsf/Section.java |  6 +--
 .../java/org/apache/poi/hpsf/VariantSupport.java   |  2 +-
 poi/src/main/java/org/apache/poi/hpsf/Vector.java  |  2 +-
 .../poi/poifs/crypt/ChunkedCipherOutputStream.java | 12 ++---
 .../poifs/crypt/cryptoapi/CryptoAPIDecryptor.java  |  8 +--
 .../apache/poi/poifs/crypt/xor/XORDecryptor.java   |  4 +-
 .../apache/poi/poifs/crypt/xor/XOREncryptor.java   |  4 +-
 .../poi/poifs/nio/ByteArrayBackedDataSource.java   | 10 ++--
 src/resources/ooxml-lite-report.xsb                |  1 +
 test-data/poi-integration-exceptions.csv           |  3 +-
 37 files changed, 147 insertions(+), 119 deletions(-)

diff --git 
a/poi-integration/src/test/java/org/apache/poi/stress/TestAllFiles.java 
b/poi-integration/src/test/java/org/apache/poi/stress/TestAllFiles.java
index 08a79f8428..a88ea32396 100644
--- a/poi-integration/src/test/java/org/apache/poi/stress/TestAllFiles.java
+++ b/poi-integration/src/test/java/org/apache/poi/stress/TestAllFiles.java
@@ -103,6 +103,9 @@ public class TestAllFiles {
         // invalid files
         "spreadsheet/bug69769.xlsx",
 
+        // fuzz files
+        
"slideshow/clusterfuzz-testcase-minimized-POIHSLFFuzzer-4630915954114560.ppt",
+
         // NOTE: Expected failures should usually be added in file 
"poi-integration-exceptions.csv" instead
         // of being listed here in order to also verify the expected exception 
details!
     };
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFDrawing.java 
b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFDrawing.java
index 9291ffe31f..b9d954353f 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFDrawing.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFDrawing.java
@@ -45,7 +45,11 @@ public class XSLFDrawing {
             // ignore them for now
             if (o instanceof CTNonVisualDrawingProps) {
                 CTNonVisualDrawingProps p = (CTNonVisualDrawingProps)o;
-                sheet.registerShapeId((int)p.getId());
+                try {
+                    sheet.registerShapeId(Math.toIntExact(p.getId()));
+                } catch (ArithmeticException e) {
+                    throw new IllegalStateException("Int overflow with drawing 
id " + p.getId());
+                }
             }
         }
     }
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSimpleShape.java 
b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSimpleShape.java
index 6a1c6bb4ce..8f562bbee0 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSimpleShape.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSimpleShape.java
@@ -676,7 +676,12 @@ public abstract class XSLFSimpleShape extends XSLFShape
             CTShapeStyle style = getSpStyle();
             if (style != null && style.getEffectRef() != null) {
                 // 1-based index of a shadow style within the style matrix
-                int idx = (int) style.getEffectRef().getIdx();
+                int idx;
+                try {
+                    idx = Math.toIntExact(style.getEffectRef().getIdx());
+                } catch (ArithmeticException e) {
+                    throw new IllegalStateException("Int overflow with effect 
ref id " + style.getEffectRef().getIdx());
+                }
                 if(idx != 0) {
                     CTStyleMatrix styleMatrix = 
getSheet().getTheme().getXmlObject().getThemeElements().getFmtScheme();
                     CTEffectStyleItem ef = 
styleMatrix.getEffectStyleLst().getEffectStyleArray(idx - 1);
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTabStop.java 
b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTabStop.java
index 3d699af3ab..a3c92f63a6 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTabStop.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTabStop.java
@@ -33,7 +33,7 @@ public class XSLFTabStop implements TabStop {
 
     /** position in EMUs */
     public int getPosition() {
-        return (int)POIXMLUnits.parseLength(tabStop.xgetPos());
+        return Math.toIntExact(POIXMLUnits.parseLength(tabStop.xgetPos()));
     }
 
     /** position in EMUs */
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java
index c673f2c704..d9866ac215 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java
@@ -48,7 +48,7 @@ public final class XSSFChildAnchor extends XSSFAnchor {
     }
 
     public int getDx1() {
-        return (int)t2d.getOff().getX();
+        return Math.toIntExact((Long)t2d.getOff().getX());
     }
 
     public void setDx1(int dx1) {
@@ -56,7 +56,7 @@ public final class XSSFChildAnchor extends XSSFAnchor {
     }
 
     public int getDy1() {
-        return (int)t2d.getOff().getY();
+        return Math.toIntExact((Long)t2d.getOff().getY());
     }
 
     public void setDy1(int dy1) {
@@ -64,7 +64,7 @@ public final class XSSFChildAnchor extends XSSFAnchor {
     }
 
     public int getDy2() {
-        return (int)(getDy1() + t2d.getExt().getCy());
+        return Math.toIntExact(getDy1() + t2d.getExt().getCy());
     }
 
     public void setDy2(int dy2) {
@@ -72,7 +72,7 @@ public final class XSSFChildAnchor extends XSSFAnchor {
     }
 
     public int getDx2() {
-        return (int)(getDx1() + t2d.getExt().getCx());
+        return Math.toIntExact(getDx1() + t2d.getExt().getCx());
     }
 
     public void setDx2(int dx2) {
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFColor.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFColor.java
index 5b45b136f7..b03ab9a660 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFColor.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFColor.java
@@ -248,7 +248,7 @@ public class XSSFColor extends ExtendedColor {
      */
     @Override
     public int getTheme() {
-        return (int) ctColor.getTheme();
+        return Math.toIntExact(ctColor.getTheme());
     }
 
     /**
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingRule.java
 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingRule.java
index a6f21e5e7b..987dc81b73 100644
--- 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingRule.java
+++ 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingRule.java
@@ -114,7 +114,7 @@ public class XSSFConditionalFormattingRule implements 
ConditionalFormattingRule
         StylesTable styles = _sh.getWorkbook().getStylesSource();
         CTDxf dxf = null;
         if(styles._getDXfsSize() > 0 && _cfRule.isSetDxfId()){
-            int dxfId = (int)_cfRule.getDxfId();
+            int dxfId = Math.toIntExact(_cfRule.getDxfId());
             dxf = styles.getDxfAt(dxfId);
         }
         if(create && dxf == null) {
@@ -349,7 +349,7 @@ public class XSSFConditionalFormattingRule implements 
ConditionalFormattingRule
         if(dxf == null || !dxf.isSetNumFmt()) return null;
 
         CTNumFmt numFmt = dxf.getNumFmt();
-        return new ExcelNumberFormat((int) numFmt.getNumFmtId(), 
numFmt.getFormatCode());
+        return new ExcelNumberFormat(Math.toIntExact(numFmt.getNumFmtId()), 
numFmt.getFormatCode());
     }
 
     /**
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataBarFormatting.java
 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataBarFormatting.java
index b58fc5b147..9fefa19bc8 100644
--- 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataBarFormatting.java
+++ 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataBarFormatting.java
@@ -52,14 +52,14 @@ public class XSSFDataBarFormatting implements 
DataBarFormatting {
     }
 
     public int getWidthMin() {
-        return (int)_databar.getMinLength();
+        return Math.toIntExact(_databar.getMinLength());
     }
     public void setWidthMin(int width) {
         _databar.setMinLength(width);
     }
 
     public int getWidthMax() {
-        return (int)_databar.getMaxLength();
+        return Math.toIntExact(_databar.getMaxLength());
     }
     public void setWidthMax(int width) {
         _databar.setMaxLength(width);
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDxfStyleProvider.java
 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDxfStyleProvider.java
index f161e8f65c..d4b6eff45d 100644
--- 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDxfStyleProvider.java
+++ 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDxfStyleProvider.java
@@ -53,7 +53,7 @@ public class XSSFDxfStyleProvider implements 
DifferentialStyleProvider {
             font = dxf.isSetFont() ? new XSSFFontFormatting(dxf.getFont(), 
colorMap) : null;
             if (dxf.isSetNumFmt()) {
                 CTNumFmt numFmt = dxf.getNumFmt();
-                number = new ExcelNumberFormat((int) numFmt.getNumFmtId(), 
numFmt.getFormatCode());
+                number = new 
ExcelNumberFormat(Math.toIntExact(numFmt.getNumFmtId()), 
numFmt.getFormatCode());
             } else {
                 number = null;
             }
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFontFormatting.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFontFormatting.java
index 7a4c01dc66..85c8bfcf14 100644
--- 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFontFormatting.java
+++ 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFontFormatting.java
@@ -92,7 +92,7 @@ public class XSSFFontFormatting implements FontFormatting {
 
         int idx = 0;
         CTColor color = _font.getColorArray(0);
-        if(color.isSetIndexed()) idx = (int)color.getIndexed();
+        if(color.isSetIndexed()) idx = Math.toIntExact(color.getIndexed());
         return (short)idx;
     }
 
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFName.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFName.java
index 476671a48a..163550506f 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFName.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFName.java
@@ -240,7 +240,7 @@ public final class XSSFName implements Name {
      */
     @Override
     public int getSheetIndex() {
-        return _ctName.isSetLocalSheetId() ? (int) _ctName.getLocalSheetId() : 
-1;
+        return _ctName.isSetLocalSheetId() ? 
Math.toIntExact(_ctName.getLocalSheetId()) : -1;
     }
 
     /**
@@ -283,7 +283,7 @@ public final class XSSFName implements Name {
      * @return the function group index that defines the general category for 
the function
      */
     public int getFunctionGroupId() {
-        return (int) _ctName.getFunctionGroupId();
+        return Math.toIntExact(_ctName.getFunctionGroupId());
     }
 
     /**
@@ -296,7 +296,7 @@ public final class XSSFName implements Name {
     public String getSheetName() {
         if (_ctName.isSetLocalSheetId()) {
             // Given as explicit sheet id
-            int sheetId = (int)_ctName.getLocalSheetId();
+            int sheetId = Math.toIntExact(_ctName.getLocalSheetId());
             return _workbook.getSheetName(sheetId);
         }
         String ref = getRefersToFormula();
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOptimiser.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOptimiser.java
index 9d2ad208b6..f52ebfce76 100755
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOptimiser.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOptimiser.java
@@ -172,7 +172,7 @@ public final class XSSFOptimiser {
             for (int i = 0; i < ctXfs.sizeOfXfArray(); i++) {
                 CTXf xf = ctXfs.getXfArray(i);
                 if (xf.isSetFontId()) {
-                    int oldFontId = (int) xf.getFontId();
+                    int oldFontId = Math.toIntExact(xf.getFontId());
                     int canonicalFontId = 
oldToCanonical.getOrDefault(oldFontId, oldFontId);
                     if (canonicalFontId != oldFontId) {
                         xf.setFontId(canonicalFontId);
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java
index 5e0c9de8fa..0840483e06 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java
@@ -995,7 +995,7 @@ public class XSSFSimpleShape extends XSSFShape implements 
Iterable<XSSFTextParag
                 CTSRgbColor clr = fill.isSetSrgbClr() ? fill.getSrgbClr() : 
fill.addNewSrgbClr();
                 clr.setVal(xlsColor.getRgb());
             } else if (xlsColor.isSetIndexed()) {
-                HSSFColor indexed = HSSFColor.getIndexHash().get((int) 
xlsColor.getIndexed());
+                HSSFColor indexed = 
HSSFColor.getIndexHash().get(Math.toIntExact(xlsColor.getIndexed()));
                 if (indexed != null) {
                     byte[] rgb = new byte[3];
                     rgb[0] = (byte) indexed.getTriplet()[0];
@@ -1015,7 +1015,7 @@ public class XSSFSimpleShape extends XSSFShape implements 
Iterable<XSSFTextParag
 
     @Override
     public int getShapeId() {
-        return (int) ctShape.getNvSpPr().getCNvPr().getId();
+        return Math.toIntExact(ctShape.getNvSpPr().getCNvPr().getId());
     }
 
     @Override
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTableStyle.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTableStyle.java
index f5cfaf425b..ca6211db9e 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTableStyle.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTableStyle.java
@@ -90,11 +90,11 @@ public class XSSFTableStyle implements TableStyle {
             TableStyleType type = 
TableStyleType.valueOf(element.getType().toString());
             DifferentialStyleProvider dstyle = null;
             if (element.isSetDxfId()) {
-                int idx = (int) element.getDxfId();
+                int idx = Math.toIntExact(element.getDxfId());
                 CTDxf dxf;
                 dxf = dxfList.get(idx);
                 int stripeSize = 0;
-                if (element.isSetSize()) stripeSize = (int) element.getSize();
+                if (element.isSetSize()) stripeSize = 
Math.toIntExact(element.getSize());
                 if (dxf != null) dstyle = new XSSFDxfStyleProvider(dxf, 
stripeSize, colorMap);
             }
             elementMap.put(type, dstyle);
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
index 1edd31d614..4aec062781 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
@@ -979,7 +979,7 @@ public class XSSFWorkbook extends POIXMLDocument implements 
Workbook, Date1904Su
         outerloop:
         while(true) {
             for(XSSFSheet sh : sheets) {
-                sheetNumber = (int)Math.max(sh.sheet.getSheetId() + 1, 
sheetNumber);
+                sheetNumber = Math.toIntExact(Math.max(sh.sheet.getSheetId() + 
1, sheetNumber));
             }
 
             // Bug 57165: We also need to check that the resulting file name 
is not already taken
@@ -1046,7 +1046,7 @@ public class XSSFWorkbook extends POIXMLDocument 
implements Workbook, Date1904Su
     public int getActiveSheetIndex() {
         //activeTab (Active Sheet Index) Specifies an unsignedInt
         //that contains the index to the active sheet in this book view.
-        return 
(int)workbook.getBookViews().getWorkbookViewArray(0).getActiveTab();
+        return 
Math.toIntExact(workbook.getBookViews().getWorkbookViewArray(0).getActiveTab());
     }
 
     /**
@@ -2062,7 +2062,7 @@ public class XSSFWorkbook extends POIXMLDocument 
implements Workbook, Date1904Su
      */
     protected void onDeleteFormula(XSSFCell cell){
         if(calcChain != null) {
-            int sheetId = (int)cell.getSheet().sheet.getSheetId();
+            int sheetId = Math.toIntExact(cell.getSheet().sheet.getSheetId());
             calcChain.removeItem(sheetId, cell.getReference());
         }
     }
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
index 6dcee13193..a0ae0311f2 100644
--- 
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
+++ 
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
@@ -311,7 +311,7 @@ public class ColumnHelper {
     public int getColDefaultStyle(long index) {
         final CTCol column = getColumn(index, false);
         if (column != null) {
-            return (int) column.getStyle();
+            return Math.toIntExact(column.getStyle());
         }
         return -1;
     }
diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfComment.java 
b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfComment.java
index 04f37e409f..ff9d0f48a9 100644
--- 
a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfComment.java
+++ 
b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfComment.java
@@ -123,7 +123,7 @@ public class HemfComment {
         @Override
         public long init(LittleEndianInputStream leis, long recordSize, long 
recordId) throws IOException {
             long startIdx = leis.getReadIndex();
-            data = new EmfCommentDataIterator(leis, (int)recordSize, 
true).next();
+            data = new EmfCommentDataIterator(leis, 
Math.toIntExact(recordSize), true).next();
             return leis.getReadIndex()-startIdx;
         }
 
@@ -152,9 +152,10 @@ public class HemfComment {
         }
 
         static void validateCommentType(final LittleEndianInputStream leis, 
HemfCommentRecordType commentType) {
-            int commentIdentifier = (int)leis.readUInt();
+            // comment identifiers are uint32 values used as bit-pattern 
identifiers, not numeric values
+            int commentIdentifier = (int) leis.readUInt();
             if (commentIdentifier == HemfCommentRecordType.emfPublic.id) {
-                commentIdentifier = (int)leis.readUInt();
+                commentIdentifier = (int) leis.readUInt();
             }
             assert(commentIdentifier == commentType.id);
         }
@@ -232,10 +233,10 @@ public class HemfComment {
                 // See the preceding table for descriptions of these record 
types.
                 // Valid comment identifier values are listed in the following 
table.
                 //
-                // If this field contains any other value, the comment record 
MUST be an EMR_COMMENT record
-                final int commentIdentifier = (int)leis.readUInt();
+                // comment identifiers are uint32 values used as bit-pattern 
identifiers, not numeric values
+                final int commentIdentifier = (int) leis.readUInt();
                 // A 32-bit unsigned integer that identifies the type of 
public comment record.
-                final int publicCommentIdentifier = (int)leis.readUInt();
+                final int publicCommentIdentifier = (int) leis.readUInt();
 
                 final boolean isEmfPublic = (commentIdentifier == 
HemfCommentRecordType.emfPublic.id);
                 leis.reset();
@@ -246,7 +247,7 @@ public class HemfComment {
                 final EmfCommentData record = commentType.constructor.get();
 
                 long readBytes = record.init(leis, dataSize);
-                final int skipBytes = (int)(recordSize-4-readBytes);
+                final int skipBytes = Math.toIntExact(recordSize-4-readBytes);
                 assert (skipBytes >= 0);
                 leis.skipFully(skipBytes);
 
@@ -331,7 +332,7 @@ public class HemfComment {
         throws IOException {
             final long startIdx = leis.getReadIndex();
             EmfComment.validateCommentType(leis, 
HemfCommentRecordType.emfPlus);
-            new HemfPlusRecordIterator(leis, 
(int)dataSize-LittleEndianConsts.INT_SIZE).forEachRemaining(records::add);
+            new HemfPlusRecordIterator(leis, 
Math.toIntExact(dataSize)-LittleEndianConsts.INT_SIZE).forEachRemaining(records::add);
             return leis.getReadIndex()-startIdx;
         }
 
@@ -385,7 +386,7 @@ public class HemfComment {
             HemfDraw.readRectL(leis, bounds);
 
             // The number of Unicode characters in the optional description 
string that follows.
-            int nDescription = (int)leis.readUInt();
+            int nDescription = Math.toIntExact(leis.readUInt());
 
             byte[] buf = IOUtils.safelyAllocate(nDescription * 2L, 
HwmfPicture.getMaxRecordLength());
             leis.readFully(buf);
@@ -448,7 +449,7 @@ public class HemfComment {
             HemfDraw.readRectL(leis, bounds);
 
             // A 32-bit unsigned integer that specifies the number of graphics 
formats contained in this record.
-            int countFormats = (int)leis.readUInt();
+            int countFormats = Math.toIntExact(leis.readUInt());
             for (int i=0; i<countFormats; i++) {
                 EmfCommentDataFormat fmt = new EmfCommentDataFormat();
                 long readBytes = fmt.init(leis, dataSize, startIdx);
@@ -602,7 +603,7 @@ public class HemfComment {
 
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the
             // WMF metafile in the WinMetafile field.
-            int winMetafileSize = (int)leis.readUInt();
+            int winMetafileSize = Math.toIntExact(leis.readUInt());
 
             wmfData = IOUtils.safelyAllocate(winMetafileSize, 
HwmfPicture.getMaxRecordLength());
             // some emf comments are truncated, so we don't use readFully here
diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfDraw.java 
b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfDraw.java
index daa9bb4bc6..716b2ace2a 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfDraw.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfDraw.java
@@ -143,7 +143,7 @@ public final class HemfDraw {
              *
              * Any extra points MUST be ignored.
              */
-            final int count = (int)leis.readUInt();
+            final int count = Math.toIntExact(leis.readUInt());
             final int points = Math.min(count, 16384);
             size += LittleEndianConsts.INT_SIZE;
 
@@ -275,7 +275,7 @@ public final class HemfDraw {
             long size = readRectL(leis, bounds);
 
             // see PolyBezier about limits
-            final int count = (int)leis.readUInt();
+            final int count = Math.toIntExact(leis.readUInt());
             final int points = Math.min(count, 16384);
             size += LittleEndianConsts.INT_SIZE;
 
@@ -506,7 +506,7 @@ public final class HemfDraw {
 
             // An array of 32-bit unsigned integers that specifies the point 
count for each polygon.
             IOUtils.safelyAllocateCheck(numberOfPolygons, 
MAX_NUMBER_OF_POLYGONS);
-            long[] polygonPointCount = new long[(int)numberOfPolygons];
+            long[] polygonPointCount = new 
long[Math.toIntExact(numberOfPolygons)];
 
             size += numberOfPolygons * LittleEndianConsts.INT_SIZE;
 
@@ -518,7 +518,7 @@ public final class HemfDraw {
             for (long nPoints : polygonPointCount) {
                 // An array of WMF PointL objects that specifies the points 
for all polygons in logical units.
                 // The number of points is specified by the Count field value.
-                Path2D poly = new Path2D.Double(Path2D.WIND_EVEN_ODD, 
(int)nPoints);
+                Path2D poly = new Path2D.Double(Path2D.WIND_EVEN_ODD, 
Math.toIntExact(nPoints));
                 for (int i=0; i<nPoints; i++) {
                     size += readPoint(leis, pnt);
                     if (i == 0) {
@@ -827,8 +827,8 @@ public final class HemfDraw {
             long size = readRectL(leis, bounds);
 
             // A 32-bit unsigned integer that defines the x-coordinate of the 
point.
-            int width = (int)leis.readUInt();
-            int height = (int)leis.readUInt();
+            int width = Math.toIntExact(leis.readUInt());
+            int height = Math.toIntExact(leis.readUInt());
             corners.setSize(width, height);
 
             return size + 2*LittleEndianConsts.INT_SIZE;
@@ -945,7 +945,7 @@ public final class HemfDraw {
         @Override
         public long init(LittleEndianInputStream leis, long recordSize, long 
recordId) throws IOException {
             long size = readRectL(leis, bounds);
-            int count = (int)leis.readUInt();
+            int count = Math.toIntExact(leis.readUInt());
             size += LittleEndianConsts.INT_SIZE;
             Point2D[] points = new Point2D[count];
             for (int i=0; i<count; i++) {
diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java 
b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java
index 477b6ecb00..6273ab5ff7 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java
@@ -72,7 +72,7 @@ public final class HemfFill {
         public long init(LittleEndianInputStream leis, long recordSize, long 
recordId) throws IOException {
             // A 32-bit unsigned integer that specifies the polygon fill mode 
and
             // MUST be in the PolygonFillMode enumeration.
-            polyFillMode = HwmfPolyfillMode.valueOf((int)leis.readUInt());
+            polyFillMode = 
HwmfPolyfillMode.valueOf(Math.toIntExact(leis.readUInt()));
             return LittleEndianConsts.INT_SIZE;
         }
 
@@ -95,7 +95,7 @@ public final class HemfFill {
             size += colorRef.init(leis);
             // A 32-bit unsigned integer that specifies how to use the Color 
value to determine the area for
             // the flood fill operation. The value MUST be in the FloodFill 
enumeration
-            mode = HwmfFloodFillMode.values()[(int)leis.readUInt()];
+            mode = 
HwmfFloodFillMode.values()[Math.toIntExact(leis.readUInt())];
             return size + LittleEndianConsts.INT_SIZE;
         }
 
@@ -135,7 +135,7 @@ public final class HemfFill {
             // A 32-bit unsigned integer that specifies the raster operation 
code. This code defines how the
             // color data of the source rectangle is to be combined with the 
color data of the destination
             // rectangle and optionally a brush pattern, to achieve the final 
color.
-            int rasterOpIndex = (int)leis.readUInt();
+            int rasterOpIndex = Math.toIntExact(leis.readUInt());
 
             rasterOperation = HwmfTernaryRasterOp.valueOf(rasterOpIndex >>> 
16);
 
@@ -148,14 +148,14 @@ public final class HemfFill {
 
             size += bkColorSrc.init(leis);
 
-            colorUsage = ColorUsage.valueOf((int)leis.readUInt());
+            colorUsage = ColorUsage.valueOf(Math.toIntExact(leis.readUInt()));
 
             // A 32-bit unsigned integer that specifies the offset, in bytes, 
from the
             // start of this record to the source bitmap header in the 
BitmapBuffer field.
-            final int offBmiSrc = (int)leis.readUInt();
+            final int offBmiSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap header.
-            final int cbBmiSrc = (int)leis.readUInt();
+            final int cbBmiSrc = Math.toIntExact(leis.readUInt());
             size += 3*LittleEndianConsts.INT_SIZE;
             if (size >= recordSize) {
                 return size;
@@ -163,10 +163,10 @@ public final class HemfFill {
 
             // A 32-bit unsigned integer that specifies the offset, in bytes, 
from the
             // start of this record to the source bitmap bits in the 
BitmapBuffer field.
-            final int offBitsSrc = (int)leis.readUInt();
+            final int offBitsSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap bits.
-            final int cbBitsSrc = (int)leis.readUInt();
+            final int cbBitsSrc = Math.toIntExact(leis.readUInt());
             size += 2*LittleEndianConsts.INT_SIZE;
 
             if (size >= recordSize) {
@@ -255,17 +255,17 @@ public final class HemfFill {
 
             // A 32-bit unsigned integer that specifies the offset, in bytes 
from the start
             // of this record to the source bitmap header.
-            int offBmiSrc = (int)leis.readUInt();
+            int offBmiSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap header.
-            int cbBmiSrc = (int)leis.readUInt();
+            int cbBmiSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit unsigned integer that specifies the offset, in bytes, 
from the
             // start of this record to the source bitmap bits.
-            int offBitsSrc = (int)leis.readUInt();
+            int offBitsSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap bits.
-            int cbBitsSrc = (int)leis.readUInt();
+            int cbBitsSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit unsigned integer that specifies how to interpret 
values in the color table
             // in the source bitmap header. This value MUST be in the 
DIBColors enumeration
@@ -275,7 +275,7 @@ public final class HemfFill {
             // These codes define how the color data of the source rectangle 
is to be combined with the color data
             // of the destination rectangle and optionally a brush pattern, to 
achieve the final color.
             // The value MUST be in the WMF Ternary Raster Operation 
enumeration
-            int rasterOpIndex = (int)leis.readUInt();
+            int rasterOpIndex = Math.toIntExact(leis.readUInt());
             rasterOperation = HwmfTernaryRasterOp.valueOf(rasterOpIndex >>> 
16);
 
             // A 32-bit signed integer that specifies the logical width of the 
destination rectangle.
@@ -339,7 +339,8 @@ public final class HemfFill {
             // A 32-bit unsigned integer that specifies the size of region 
data, in bytes.
             long rgnDataSize = leis.readUInt();
             // A 32-bit unsigned integer that specifies the brush EMF Object 
Table index.
-            brushIndex = (int)leis.readUInt();
+            // Stock object references can have the high bit set, so use (int) 
cast.
+            brushIndex = (int) leis.readUInt();
             // A 32-bit signed integer that specifies the width of the 
vertical brush stroke, in logical units.
             int width = leis.readInt();
             // A 32-bit signed integer that specifies the height of the 
horizontal brush stroke, in logical units.
@@ -452,7 +453,8 @@ public final class HemfFill {
             long size = readRectL(leis, bounds);
             // A 32-bit unsigned integer that specifies the size of region 
data, in bytes.
             long rgnDataSize = leis.readUInt();
-            brushIndex = (int)leis.readUInt();
+            // Stock object references can have the high bit set, so use (int) 
cast.
+            brushIndex = (int) leis.readUInt();
             size += 2*LittleEndianConsts.INT_SIZE;
             size += readRgnData(leis, rgnRects);
             return size;
@@ -500,7 +502,7 @@ public final class HemfFill {
             // A 32-bit unsigned integer that specifies the size of region 
data in bytes
             long rgnDataSize = leis.readUInt();
             // A 32-bit unsigned integer that specifies the way to use the 
region.
-            regionMode = HwmfRegionMode.valueOf((int)leis.readUInt());
+            regionMode = 
HwmfRegionMode.valueOf(Math.toIntExact(leis.readUInt()));
             long size = 2L * LittleEndianConsts.INT_SIZE;
 
             // If RegionMode is RGN_COPY, this data can be omitted and the 
clip region
@@ -625,20 +627,20 @@ public final class HemfFill {
             size += readXForm(leis, xFormSrc);
             size += bkColorSrc.init(leis);
 
-            usageSrc = ColorUsage.valueOf((int)leis.readUInt());
+            usageSrc = ColorUsage.valueOf(Math.toIntExact(leis.readUInt()));
 
 
             // A 32-bit unsigned integer that specifies the offset, in bytes, 
from the
             // start of this record to the source bitmap header in the 
BitmapBuffer field.
-            final int offBmiSrc = (int)leis.readUInt();
+            final int offBmiSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap header.
-            final int cbBmiSrc = (int)leis.readUInt();
+            final int cbBmiSrc = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies the offset, in bytes, 
from the
             // start of this record to the source bitmap bits in the 
BitmapBuffer field.
-            final int offBitsSrc = (int)leis.readUInt();
+            final int offBitsSrc = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap bits.
-            final int cbBitsSrc = (int)leis.readUInt();
+            final int cbBitsSrc = Math.toIntExact(leis.readUInt());
 
             // A 32-bit signed integer that specifies the logical width of the 
source rectangle.
             // This value MUST be greater than zero.
@@ -703,21 +705,21 @@ public final class HemfFill {
             size += readBounds2(leis, src);
             // A 32-bit unsigned integer that specifies the offset, in bytes, 
from the
             // start of this record to the source bitmap header in the 
BitmapBuffer field.
-            final int offBmiSrc = (int)leis.readUInt();
+            final int offBmiSrc = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap header.
-            final int cbBmiSrc = (int)leis.readUInt();
+            final int cbBmiSrc = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies the offset, in bytes, 
from the
             // start of this record to the source bitmap bits in the 
BitmapBuffer field.
-            final int offBitsSrc = (int)leis.readUInt();
+            final int offBitsSrc = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies the size, in bytes, of 
the source bitmap bits.
-            final int cbBitsSrc = (int)leis.readUInt();
+            final int cbBitsSrc = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies how to interpret 
values in the color table
             // in the source bitmap header. This value MUST be in the 
DIBColors enumeration
-            usageSrc = ColorUsage.valueOf((int)leis.readUInt());
+            usageSrc = ColorUsage.valueOf(Math.toIntExact(leis.readUInt()));
             // A 32-bit unsigned integer that specifies the first scan line in 
the array.
-            final int iStartScan = (int)leis.readUInt();
+            final int iStartScan = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies the number of scan 
lines.
-            final int cScans = (int)leis.readUInt();
+            final int cScans = Math.toIntExact(leis.readUInt());
             size += 7*LittleEndianConsts.INT_SIZE;
 
             size += readBitmap(leis, bitmap, startIdx, offBmiSrc, cbBmiSrc, 
offBitsSrc, cbBitsSrc);
diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFont.java 
b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFont.java
index c7f189f1d5..080c2d5ce4 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFont.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFont.java
@@ -378,7 +378,7 @@ public class HemfFont extends HwmfFont {
             // A 32-bit unsigned integer that specifies the point size at 
which font
             //hinting is performed. If set to zero, font hinting is performed 
at the point size corresponding
             //to the Height field in the LogFont object in the LogFont field.
-            logPan.styleSize = (int)leis.readUInt();
+            logPan.styleSize = Math.toIntExact(leis.readUInt());
 
             int match = leis.readInt();
 
diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfPalette.java 
b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfPalette.java
index 607e30244e..e1e24a475a 100644
--- 
a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfPalette.java
+++ 
b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfPalette.java
@@ -41,9 +41,10 @@ public class HemfPalette {
             /*
              * A 32-bit unsigned integer that specifies either the index of a 
LogPalette object
              * in the EMF Object Table or the value DEFAULT_PALETTE, which is 
the index
-             * of a stock object palette from the StockObject enumeration
+             * of a stock object palette from the StockObject enumeration.
+             * Stock object references can have the high bit set, so use (int) 
cast.
              */
-            paletteIndex = (int)leis.readUInt();
+            paletteIndex = (int) leis.readUInt();
             return LittleEndianConsts.INT_SIZE;
         }
 
@@ -68,9 +69,9 @@ public class HemfPalette {
             start = 0x0300;
             /* A 32-bit unsigned integer that specifies the index of the 
logical palette object
              * in the EMF Object Table. This index MUST be saved so that this 
object can be
-             * reused or modified.
+             * reused or modified. Stock object references can have the high 
bit set, so use (int) cast.
              */
-            paletteIndex = (int)leis.readUInt();
+            paletteIndex = (int) leis.readUInt();
             /* A 16-bit unsigned integer that specifies the version number of 
the system. This MUST be 0x0300. */
             int version = leis.readUShort();
             assert(version == 0x0300);
@@ -117,11 +118,12 @@ public class HemfPalette {
         @Override
         public long init(LittleEndianInputStream leis, long recordSize, long 
recordId) throws IOException {
             // A 32-bit unsigned integer that specifies the palette EMF Object 
Table index.
-            paletteIndex = (int)leis.readUInt();
+            // Stock object references can have the high bit set, so use (int) 
cast.
+            paletteIndex = (int) leis.readUInt();
             // A 32-bit unsigned integer that specifies the index of the first 
entry to set.
-            start = (int)leis.readUInt();
+            start = Math.toIntExact(leis.readUInt());
             // A 32-bit unsigned integer that specifies the number of entries.
-            int nbrOfEntries = (int)leis.readUInt();
+            int nbrOfEntries = Math.toIntExact(leis.readUInt());
             int size = readPaletteEntries(leis, nbrOfEntries);
             return size + 3L*LittleEndianConsts.INT_SIZE;
         }
@@ -163,12 +165,13 @@ public class HemfPalette {
 
         @Override
         public long init(LittleEndianInputStream leis, long recordSize, long 
recordId) throws IOException {
-            // A 32-bit unsigned integer that specifies the index of the 
palette object in the EMF Object Table
-            paletteIndex = (int)leis.readUInt();
+            // A 32-bit unsigned integer that specifies the index of the 
palette object in the EMF Object Table.
+            // Stock object references can have the high bit set, so use (int) 
cast.
+            paletteIndex = (int) leis.readUInt();
 
             // A 32-bit unsigned integer that specifies the number of entries 
in the palette after resizing.
             // The value MUST be less than or equal to 0x00000400 and greater 
than 0x00000000.
-            numberOfEntries = (int)leis.readUInt();
+            numberOfEntries = Math.toIntExact(leis.readUInt());
 
             return 2L*LittleEndianConsts.INT_SIZE;
         }
diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/RecordUtil.java 
b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/RecordUtil.java
index 6e750da446..18e9e2ffbd 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/RecordUtil.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/RecordUtil.java
@@ -105,7 +105,7 @@ public class RecordUtil
     {
         byte parentSize = 0;
         byte numBits = 0;
-        int mask = (int) Long.parseLong( bitMask.substring( 2 ), 16 );
+        int mask = Math.toIntExact(Long.parseLong(bitMask.substring(2), 16));
 
         switch (parentType) {
             case "byte":
diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/model/PlfLfo.java 
b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/model/PlfLfo.java
index ba8e39b26c..a63c0bdeea 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/model/PlfLfo.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/model/PlfLfo.java
@@ -80,7 +80,7 @@ public class PlfLfo {
 
         IOUtils.safelyAllocateCheck(lfoMacLong, MAX_NUMBER_OF_LFO);
 
-        this._lfoMac = (int) lfoMacLong;
+        this._lfoMac = Math.toIntExact(lfoMacLong);
         _rgLfo = new LFO[_lfoMac];
         _rgLfoData = new LFOData[_lfoMac];
 
diff --git a/poi/src/main/java/org/apache/poi/hpsf/Array.java 
b/poi/src/main/java/org/apache/poi/hpsf/Array.java
index 076f1cb60a..c937bebad4 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/Array.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/Array.java
@@ -59,7 +59,7 @@ public class Array {
                 throw new IllegalPropertySetDataException(msg);
             }
 
-            int numDimensions = (int) numDimensionsUnsigned;
+            int numDimensions = Math.toIntExact(numDimensionsUnsigned);
 
             _dimensions = new ArrayDimension[numDimensions];
             for ( int i = 0; i < numDimensions; i++ ) {
@@ -102,7 +102,7 @@ public class Array {
                 numberOfScalarsLong + " in memory";
             throw new UnsupportedOperationException(msg);
         }
-        int numberOfScalars = (int) numberOfScalarsLong;
+        int numberOfScalars = Math.toIntExact(numberOfScalarsLong);
 
         IOUtils.safelyAllocateCheck(numberOfScalars, 
getMaxNumberOfArrayScalars());
 
diff --git a/poi/src/main/java/org/apache/poi/hpsf/Property.java 
b/poi/src/main/java/org/apache/poi/hpsf/Property.java
index ab6d8e1017..fa336345e5 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/Property.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/Property.java
@@ -140,7 +140,7 @@ public class Property {
             throw new UnsupportedEncodingException("Dictionary not allowed 
here");
         }
 
-        int o = (int) offset;
+        int o = Math.toIntExact(offset);
         type = LittleEndian.getUInt(src, o);
         o += LittleEndianConsts.INT_SIZE;
 
diff --git a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java 
b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java
index 39d259d14a..ee561f7edf 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java
@@ -462,7 +462,7 @@ public class PropertySet {
         o += LittleEndianConsts.SHORT_SIZE;
         format = LittleEndian.getUShort(src, o);
         o += LittleEndianConsts.SHORT_SIZE;
-        osVersion = (int) LittleEndian.getUInt(src, o);
+        osVersion = Math.toIntExact(LittleEndian.getUInt(src, o));
         o += LittleEndianConsts.INT_SIZE;
         classID = new ClassID(src, o);
         o += ClassID.LENGTH;
@@ -862,20 +862,20 @@ public class PropertySet {
     }
 
     void set1stProperty(long id, String value) {
-        getFirstSection().setProperty((int)id, value);
+        getFirstSection().setProperty(Math.toIntExact(id), value);
     }
 
     void set1stProperty(long id, int value) {
-        getFirstSection().setProperty((int)id, value);
+        getFirstSection().setProperty(Math.toIntExact(id), value);
     }
 
     void set1stProperty(long id, boolean value) {
-        getFirstSection().setProperty((int)id, value);
+        getFirstSection().setProperty(Math.toIntExact(id), value);
     }
 
     @SuppressWarnings("SameParameterValue")
     void set1stProperty(long id, byte[] value) {
-        getFirstSection().setProperty((int)id, value);
+        getFirstSection().setProperty(Math.toIntExact(id), value);
     }
 
     private static void putClassId(final UnsynchronizedByteArrayOutputStream 
out, final ClassID n) {
diff --git a/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java 
b/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java
index b08b68dfe1..2cdbe1fb47 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java
@@ -82,7 +82,15 @@ public class PropertySetFactory {
         /*int osVersion = (int)*/leis.readUInt();
         byte[] clsIdBuf = new byte[ClassID.LENGTH];
         leis.readFully(clsIdBuf);
-        int sectionCount = (int)leis.readUInt();
+        final long sectionCountLong = leis.readUInt();
+        int sectionCount;
+        try {
+            sectionCount = Math.toIntExact(sectionCountLong);
+        } catch (ArithmeticException e) {
+            throw new NoPropertySetStreamException("ByteOrder: " + byteOrder +
+                    ", format: " + format +
+                    ", sectionCount: " + sectionCountLong);
+        }
 
         if (byteOrder != PropertySet.BYTE_ORDER_ASSERTION ||
             format != PropertySet.FORMAT_ASSERTION ||
diff --git a/poi/src/main/java/org/apache/poi/hpsf/Section.java 
b/poi/src/main/java/org/apache/poi/hpsf/Section.java
index 898ba7d28b..3655103ef3 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/Section.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/Section.java
@@ -129,7 +129,7 @@ public class Section {
          * Read the offset from the stream's start and positions to
          * the section header.
          */
-        int offFix = (int)LittleEndian.getUInt(src, offset + ClassID.LENGTH);
+        int offFix = Math.toIntExact(LittleEndian.getUInt(src, offset + 
ClassID.LENGTH));
 
         // some input files have an invalid (padded?) offset, which need to be 
fixed
         // search for beginning of size field
@@ -146,12 +146,12 @@ public class Section {
         /*
          * Read the section length.
          */
-        int size = (int)Math.min(leis.readUInt(), src.length-_offset);
+        int size = Math.toIntExact(Math.min(leis.readUInt(), 
src.length-_offset));
 
         /*
          * Read the number of properties.
          */
-        final int propertyCount = (int)leis.readUInt();
+        final int propertyCount = Math.toIntExact(leis.readUInt());
 
         /*
          * Read the properties. The offset is positioned at the first
diff --git a/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java 
b/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java
index 5cc4629461..dd3c06913c 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java
@@ -169,7 +169,7 @@ public class VariantSupport extends Variant {
             final int length, final long type, final int codepage )
     throws ReadingNotSupportedException, UnsupportedEncodingException {
         final int offset = lei.getReadIndex();
-        TypedPropertyValue typedPropertyValue = new TypedPropertyValue( (int) 
type, null );
+        TypedPropertyValue typedPropertyValue = new 
TypedPropertyValue(Math.toIntExact(type), null);
         try {
             typedPropertyValue.readValue(lei);
         } catch ( UnsupportedOperationException exc ) {
diff --git a/poi/src/main/java/org/apache/poi/hpsf/Vector.java 
b/poi/src/main/java/org/apache/poi/hpsf/Vector.java
index 465eabd829..b1f2386b1e 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/Vector.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/Vector.java
@@ -41,7 +41,7 @@ public class Vector {
         if ( longLength > Integer.MAX_VALUE ) {
             throw new UnsupportedOperationException( "Vector is too long -- " 
+ longLength );
         }
-        final int length = (int) longLength;
+        final int length = Math.toIntExact(longLength);
 
         //BUG-61295 -- avoid OOM on corrupt file.  Build list instead
         //of allocating array of length "length".
diff --git 
a/poi/src/main/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java 
b/poi/src/main/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java
index f366a03f8c..32112d4bf6 100644
--- 
a/poi/src/main/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java
+++ 
b/poi/src/main/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java
@@ -138,7 +138,7 @@ public abstract class ChunkedCipherOutputStream extends 
FilterOutputStream {
 
         final int chunkMask = getChunkMask();
         while (len > 0) {
-            int posInChunk = (int)(pos & chunkMask);
+            int posInChunk = Math.toIntExact(pos & chunkMask);
             int nextLen = Math.min(chunk.length-posInChunk, len);
             System.arraycopy(b, off, chunk, posInChunk, nextLen);
             if (writePlain) {
@@ -163,11 +163,11 @@ public abstract class ChunkedCipherOutputStream extends 
FilterOutputStream {
             return;
         }
 
-        int posInChunk = (int)(pos & getChunkMask());
+        int posInChunk = Math.toIntExact(pos & getChunkMask());
 
         // normally posInChunk is 0, i.e. on the next chunk (-> index-1)
         // but if called on close(), posInChunk is somewhere within the chunk 
data
-        int index = (int)(pos >> chunkBits);
+        int index = Math.toIntExact(pos >> chunkBits);
         boolean lastChunk;
         if (posInChunk==0) {
             index--;
@@ -218,7 +218,7 @@ public abstract class ChunkedCipherOutputStream extends 
FilterOutputStream {
         if (doFinal && "IBMJCE".equals(cipher.getProvider().getName()) && 
"RC4".equals(cipher.getAlgorithm())) {
             // workaround for IBMs cipher not resetting on doFinal
 
-            int index = (int)(pos >> chunkBits);
+            int index = Math.toIntExact(pos >> chunkBits);
             boolean lastChunk;
             if (posInChunk==0) {
                 index--;
@@ -258,8 +258,8 @@ public abstract class ChunkedCipherOutputStream extends 
FilterOutputStream {
             super.close();
 
             if (fileOut != null) {
-                int oleStreamSize = 
(int)(fileOut.length()+LittleEndianConsts.LONG_SIZE);
-                calculateChecksum(fileOut, (int)pos);
+                int oleStreamSize = 
Math.toIntExact(fileOut.length()+LittleEndianConsts.LONG_SIZE);
+                calculateChecksum(fileOut, Math.toIntExact(pos));
                 dir.createDocument(DEFAULT_POIFS_ENTRY, oleStreamSize, 
this::processPOIFSWriterEvent);
                 createEncryptionInfoEntry(dir, fileOut);
             }
diff --git 
a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
 
b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
index bc6eccdaf4..866139905f 100644
--- 
a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
+++ 
b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
@@ -177,20 +177,20 @@ public class CryptoAPIDecryptor extends Decryptor {
                 CryptoAPIDocumentInputStream sbis = new 
CryptoAPIDocumentInputStream(this, IOUtils.toByteArray(dis));
                 LittleEndianInputStream leis = new 
LittleEndianInputStream(sbis)
         ) {
-            int streamDescriptorArrayOffset = (int) leis.readUInt();
+            int streamDescriptorArrayOffset = Math.toIntExact(leis.readUInt());
             /* int streamDescriptorArraySize = (int) */ leis.readUInt();
             long skipN = streamDescriptorArrayOffset - 8L;
             if (sbis.skip(skipN) < skipN) {
                 throw new EOFException("buffer underrun");
             }
             sbis.setBlock(0);
-            int encryptedStreamDescriptorCount = (int) leis.readUInt();
+            int encryptedStreamDescriptorCount = 
Math.toIntExact(leis.readUInt());
             StreamDescriptorEntry[] entries = new 
StreamDescriptorEntry[encryptedStreamDescriptorCount];
             for (int i = 0; i < encryptedStreamDescriptorCount; i++) {
                 StreamDescriptorEntry entry = new StreamDescriptorEntry();
                 entries[i] = entry;
-                entry.streamOffset = (int) leis.readUInt();
-                entry.streamSize = (int) leis.readUInt();
+                entry.streamOffset = Math.toIntExact(leis.readUInt());
+                entry.streamSize = Math.toIntExact(leis.readUInt());
                 entry.block = leis.readUShort();
                 int nameSize = leis.readUByte();
                 entry.flags = leis.readUByte();
diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XORDecryptor.java 
b/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XORDecryptor.java
index d2cebca389..7a0a7d4d22 100644
--- a/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XORDecryptor.java
+++ b/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XORDecryptor.java
@@ -123,7 +123,7 @@ public class XORDecryptor extends Decryptor {
 
         @Override
         protected int invokeCipher(int totalBytes, boolean doFinal) {
-            final int pos = (int)getPos();
+            final int pos = Math.toIntExact(getPos());
             final byte[] xorArray = 
getEncryptionInfo().getDecryptor().getSecretKey().getEncoded();
             final byte[] chunk = getChunk();
             final byte[] plain = getPlain();
@@ -168,7 +168,7 @@ public class XORDecryptor extends Decryptor {
          */
         @Override
         public void setNextRecordSize(int recordSize) {
-            final int pos = (int)getPos();
+            final int pos = Math.toIntExact(getPos());
             final byte[] chunk = getChunk();
             final int chunkMask = getChunkMask();
             recordStart = pos;
diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XOREncryptor.java 
b/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XOREncryptor.java
index 0c1cbf4932..8e73cdab94 100644
--- a/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XOREncryptor.java
+++ b/poi/src/main/java/org/apache/poi/poifs/crypt/xor/XOREncryptor.java
@@ -119,9 +119,9 @@ public class XOREncryptor extends Encryptor {
         public void setNextRecordSize(int recordSize, boolean isPlain) {
             if (recordEnd > 0 && !isPlain) {
                 // encrypt last record
-                invokeCipher((int)getPos(), true);
+                invokeCipher(Math.toIntExact(getPos()), true);
             }
-            recordStart = (int)getTotalPos()+4;
+            recordStart = Math.toIntExact(getTotalPos())+4;
             recordEnd = recordStart+recordSize;
         }
 
diff --git 
a/poi/src/main/java/org/apache/poi/poifs/nio/ByteArrayBackedDataSource.java 
b/poi/src/main/java/org/apache/poi/poifs/nio/ByteArrayBackedDataSource.java
index 15c4f6ff07..fcf280693b 100644
--- a/poi/src/main/java/org/apache/poi/poifs/nio/ByteArrayBackedDataSource.java
+++ b/poi/src/main/java/org/apache/poi/poifs/nio/ByteArrayBackedDataSource.java
@@ -51,8 +51,8 @@ public class ByteArrayBackedDataSource extends DataSource {
          );
       }
 
-      int toRead = (int)Math.min(length, size - position);
-      return ByteBuffer.wrap(buffer, (int)position, toRead);
+      int toRead = Math.toIntExact(Math.min(length, size - position));
+      return ByteBuffer.wrap(buffer, Math.toIntExact(position), toRead);
    }
 
    @Override
@@ -64,7 +64,7 @@ public class ByteArrayBackedDataSource extends DataSource {
       }
 
       // Now copy
-      src.get(buffer, (int)position, src.capacity());
+      src.get(buffer, Math.toIntExact(position), src.capacity());
 
       // Update size if needed
       if(endPosition > size) {
@@ -84,13 +84,13 @@ public class ByteArrayBackedDataSource extends DataSource {
 
       long totalLen = difference+buffer.length;
       byte[] nb = IOUtils.safelyAllocate(totalLen, MAX_RECORD_LENGTH);
-      System.arraycopy(buffer, 0, nb, 0, (int)size);
+      System.arraycopy(buffer, 0, nb, 0, Math.toIntExact(size));
       buffer = nb;
    }
 
    @Override
    public void copyTo(OutputStream stream) throws IOException {
-      stream.write(buffer, 0, (int)size);
+      stream.write(buffer, 0, Math.toIntExact(size));
    }
 
    @Override
diff --git a/src/resources/ooxml-lite-report.xsb 
b/src/resources/ooxml-lite-report.xsb
index 2120d975b8..0a06847fcf 100644
--- a/src/resources/ooxml-lite-report.xsb
+++ b/src/resources/ooxml-lite-report.xsb
@@ -1187,3 +1187,4 @@ stholesizepercenta3d2type
 stholesizeubyte577atype
 chartspace67aadoctype
 ctsupplementalfonta06etype
+timestampvalidationdataelement
diff --git a/test-data/poi-integration-exceptions.csv 
b/test-data/poi-integration-exceptions.csv
index 823593fd63..31e40f8f92 100644
--- a/test-data/poi-integration-exceptions.csv
+++ b/test-data/poi-integration-exceptions.csv
@@ -159,6 +159,7 @@ 
document/clusterfuzz-testcase-minimized-POIHWPFFuzzer-5418937293340672.doc,"hand
 
document/clusterfuzz-testcase-minimized-POIHWPFFuzzer-5418937293340672.doc,extract,HPSF,,java.lang.IllegalArgumentException,Had
 unexpected type of entry for name,
 
document/clusterfuzz-testcase-minimized-POIHWPFFuzzer-5418937293340672.doc,additional,HPSF,,java.lang.IllegalArgumentException,name
 cannot be empty,
 
slideshow/clusterfuzz-testcase-minimized-POIHSLFFuzzer-4630915954114560.ppt,handle,HSLF,,java.lang.IllegalStateException,Did
 not have a container for fetching children,
+slideshow/clusterfuzz-testcase-minimized-POIHSLFFuzzer-4630915954114560.ppt,additional,HPSF,,java.lang.ArithmeticException,integer
 overflow,
 
spreadsheet/clusterfuzz-testcase-minimized-POIHSSFFuzzer-5285517825277952.xls,"handle,extract",HSSF,,java.lang.IllegalArgumentException,Had
 unexpected type of child at index 0,
 
spreadsheet/clusterfuzz-testcase-minimized-POIHSSFFuzzer-5285517825277952.xls,handle,HPSF,,org.opentest4j.AssertionFailedError,expected:
 <true> but was: <false>,
 
spreadsheet/clusterfuzz-testcase-minimized-POIHSSFFuzzer-5285517825277952.xls,extract,HPSF,,java.lang.IllegalArgumentException,Had
 unexpected type of child at index 0,
@@ -349,7 +350,7 @@ 
slideshow/clusterfuzz-testcase-minimized-POIXSLFFuzzer-4838644450394112.pptx,han
 
slideshow/clusterfuzz-testcase-minimized-POIXSLFFuzzer-4986044400861184.pptx,handle,XSLF,,java.lang.IllegalArgumentException,No
 part found for relationship,
 
diagram/clusterfuzz-testcase-minimized-POIVisioFuzzer-5842659694215168.vsdx,extract,"XDGF,OPC",,java.io.IOException,org.apache.poi.ooxml.POIXMLException:
 /visio/pages/pages.xml: /visio/pages/page1.xml,
 
diagram/clusterfuzz-testcase-minimized-POIVisioFuzzer-5842659694215168.vsdx,handle,XDGF,,org.apache.poi.ooxml.POIXMLException,/visio/pages/pages.xml:
 /visio/pages/page1.xml,
-document/clusterfuzz-testcase-minimized-POIHWPFFuzzer-5195207308541952.doc,additional,HPSF,,org.apache.poi.hpsf.HPSFRuntimeException,Value
 type of property ID 1 is not VT_I2,
+document/clusterfuzz-testcase-minimized-POIHWPFFuzzer-5195207308541952.doc,additional,HPSF,,java.lang.ArithmeticException,integer
 overflow,
 
document/clusterfuzz-testcase-minimized-POIHWPFFuzzer-5195207308541952.doc,handle,HWPF,,java.lang.IndexOutOfBoundsException,Block
 111 not found,
 
document/clusterfuzz-testcase-minimized-POIHWPFFuzzer-5195207308541952.doc,handle,HPSF,,org.opentest4j.AssertionFailedError,expected:
 <true> but was: <false>,
 
slideshow/clusterfuzz-testcase-minimized-POIXSLFFuzzer-5611274456596480.pptx,extract,"XSLF,OPC",,java.lang.IllegalArgumentException,Could
 not retrieve Ext from the XML object,


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to