Skip to content

Undefined behavior for GenericStringArray::from_iter_values if reported iterator upper bound is incorrect #1144

Closed

Description

@alamb

Describe the bug
While reviewing #197 I was able to create a reproducer that indeed caused undefined behavior

To Reproduce

use arrow::array::StringArray;


// Make an iterator that is untruthful about its actual length (say it is shorter than it really is):
#[derive(Debug, Clone)]
struct BadIterator<T> {
    /// where the iterator currently is
    cur: u64,
    /// How many items will this iterator *actually* make
    limit: u64,
    /// How many items this iterator claims it will make
    claimed: u64,
    /// What type of item to return
    pub item: T,
}

impl<T> BadIterator<T> {
    /// Create a new iterator for <limit> items, but that reports to
    /// produce <claimed> items
    fn new(limit: u64, claimed: u64, item: T) -> Self {
        Self{
            cur: 0,
            limit,
            claimed,
            item
        }
    }
}

impl <T:Clone> Iterator for BadIterator<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cur < self.limit {
            self.cur += 1;
            Some(self.item.clone())
        } else {
            None
        }
    }

    /// report whatever the iterator says to
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.claimed as usize))
    }
}


fn from_vec(v: Vec<&str>) -> StringArray {
    v.into_iter()
        .map(Some)
        .collect()
}


// This definitely causes a problem
fn use_iter_values() {
    // correctly report size:
    let array = StringArray::from_iter_values(BadIterator::new(3, 3, "foo"));
    assert_eq!(array, from_vec(vec!["foo", "foo", "foo"]));

    // incorrectly correctly report size to be 10
    let array = StringArray::from_iter_values(BadIterator::new(3, 10, "foo"));
    assert_eq!(array, from_vec(vec!["foo", "foo", "foo"]));

    // incorrectly correctly report size to be 1 (too small)
    let array = StringArray::from_iter_values(BadIterator::new(3, 1, "foo"));
    assert_eq!(array, from_vec(vec!["foo", "foo", "foo"]));
}

fn main() {
    println!("Starting...");
    use_iter_values();
    println!("Done...");
}

Results in

Starting...
Use collect
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', /Users/alamb/Software/arrow-rs/arrow/src/array/array_string.rs:101:40
stack backtrace:

And undefined behavior in MIRI

Expected behavior
Success and no undefined behavior

Additional context
Add any other context about the problem here.

Activity

  1. added
    arrow
    bug
    on Jan 8, 2022
  2. alamb commented on Jan 8, 2022

    @alamb
    ContributorAuthor

    Strangely, I don't understand the usecase of from_iter_values compared to FromIterator

  3. alamb commented on Jan 8, 2022

    @alamb
    ContributorAuthor

    It looks like DataFusion uses from_iter_values in several places (both for StringArrays and primitive arrays)

    https://github.com/apache/arrow-datafusion/search?q=from_iter_values

    However, when I was looking at the implementations of FromIterator and from_iter_values I didn't see the need for both.

  4. jorgecarleitao commented on Jan 8, 2022

    @jorgecarleitao
    Member

    Strangely, I don't understand the usecase of from_iter_values compared to FromIterator

    I think that from_iter_values leverages the invariant that there are no nulls in the iterator (AsRef<str>), while FromIterator accepts nulls / None. The two APIs are motivated by a significant performance penalty in creating the bitmap from an iterator of options (compared to the cost of an iterator of non-nullable values)

  5. changed the title [-]Undefined behavior for GenericStringArray::from_iter_values if reported iterator upper bound is incorrect[/-] [+]Undefined behavior for `GenericStringArray::from_iter_values` if reported iterator upper bound is incorrect[/+] on Jan 20, 2022
  6. added
    bug
    and removed
    bug
    on Jan 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    arrowbugsecurity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions